package cn.qzbook.redisData;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.Set;

/**
 * @Description
 * @Author zc
 * @Date 2020/11/10 上午12:54
 */
public class RedisSet {

    public static void main(String[] args) {
        testSet();
    }

    public static void testSet(){

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:application.xml");

        RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);


        Set set = null;

        //将元素加入列表
        redisTemplate.boundSetOps("set1").add("v1","v2","v3","v4","v5","v6");
        redisTemplate.boundSetOps("set2").add("v0","v2","v4","v6","v8");

        //求集合长度
        Long set1 = redisTemplate.opsForSet().size("set1");

        //求差集
        set = redisTemplate.opsForSet().difference("set1","set2");

        //求并集
        set = redisTemplate.opsForSet().intersect("set1","set2");

        //判断是否集合中元素
        boolean exists = redisTemplate.opsForSet().isMember("set","v1");

        //获取结集合所有元素
        set = redisTemplate.opsForSet().members("set1");

        //从集合中随机弹出一个元素
        String val = (String) redisTemplate.opsForSet().pop("set1");

        //随机获取一个集合的元素
        val = (String) redisTemplate.opsForSet().randomMember("set1");

        //随机获取2个结合的元素
        List<String> list =  redisTemplate.opsForSet().randomMembers("set1",2L);

        //删除一个集合的元素，参数可以是多个
        redisTemplate.opsForSet().remove("set1","v1");

        //求两个集合的并集
        redisTemplate.opsForSet().union("set1","set2");

        //求连个集合的差集，并保存到集合diff_set中
        redisTemplate.opsForSet().differenceAndStore("set1","set2","diff_set");

        //求两个集合的交集，并保存到集合inter_set中
        redisTemplate.opsForSet().intersectAndStore("set1","set2","inter_set");

        //求两个集合的并集，并保存到集合union_set中
        redisTemplate.opsForSet().unionAndStore("set1","set2","union_set");
    }

}
